<template>
  <div>
    <el-dialog title="导入简历" :visible.sync="visible" width="600px" :close-on-click-modal="false">
      <el-form ref="form" :model="dataForm" :rules="dataRule" label-width="120px">
        <el-form-item label="导入Excel文件" prop="fileData">
          <el-button type="primary" @click.stop="importExcel">导入文件</el-button>
          <a style="display: inline-block; margin-left: 20px" href="https://oss.qnhro.cn/template/resume-template.xls" download>下载模版</a>
          <el-upload
            v-show="false"
            class="upload"
            action="/upload"
            ref="upload"
            :on-change="onChange"
            :auto-upload="false"
            :show-file-list="false"
            :file-list="fileList"
            accept=".xls, .xlsx"
          >
          </el-upload>
          <div>{{dataForm.fileData?dataForm.fileData.name:''}}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn" :loading="loading" @click.stop="submit">提交</el-button>
          <el-button @click.stop="close">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'import-worker',
    data () {
      return {
        visible: false,
        loading:false,
        protocolList:[],
        projectList:[],
        fileList:[],
        dataList:[],
        dataForm:{
          fileData: null
        },
        dataRule:{
          fileData:[
            { required: true, message: '文件不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      // 获取数据列表
      init(){
        this.visible = true
      },
      importExcel(){
        this.$refs['upload'].$children[0].$refs.input.click()
      },
      onChange(file, fileList) {
        this.dataForm.fileData = file; // 保存当前选择文件
        this.readExcel(); // 调用读取数据的方法
      },
      readExcel(e){
        let that = this;
        const files = that.dataForm.fileData;
        if (!files) {
          return false;
        }
        else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())){
          this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
          return false;
        }
        const fileReader = new FileReader();
        fileReader.onload = ev => {
          const data = ev.target.result;
          const workbook = this.XLSX.read(data, {
            type: "binary"
          });
          if (workbook.SheetNames.length >= 1) {

          }
          const wsname = workbook.SheetNames[0];
          const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          that.outputs = []; //清空接收数据
          this.dataList=[];
          for (var i = 0; i < ws.length; i++) {
            let account =ws[i]["账号"].toString()
            let name = ws[i]["姓名"].toString()
            let gender = ws[i]["性别"] === "男" ? 0 : 1;
            let idCard = ws[i]["身份证"].toString()
            let mobile = ws[i]["联系方式"].toString()
            let address = ws[i]["户籍地址"].toString()
            let bankCard = ws[i]["工资卡卡号"].toString()
            let factoryName = ws[i]["派驻单位"].toString()
            let bank = ws[i]["银行行别及开户地址"].toString()
            let workExperience = ws[i]["工作经历"].toString()
            let model = {
              "account": account,
              "name": name,
              "gender": gender,
              "bankCard": bankCard,
              "bank": bank,
              "idCard": idCard,
              "mobile": mobile,
              "address": address,
              "factoryName": factoryName,
              "workExperience": workExperience
            }
            this.dataList.unshift(model);
          }
          this.$refs.upload.value = "";
        }
        fileReader.readAsBinaryString(files.raw);
      },
      downloadFile (url, filename) {
        function getBlob (url) {
          return new Promise(resolve => {
            const xhr = new XMLHttpRequest();

            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = () => {
              if (xhr.status === 200) {
                resolve(xhr.response);
              }
            };
            xhr.send();
          });
        }
        //下载文件
        function saveAs (blob, filename) {
          const elelink = document.createElement("a");
          elelink.style.display = 'none';
          elelink.download = filename;
          console.log(url, filename)
          elelink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elelink);
          elelink.click();
          document.body.removeChild(elelink);
        }
        // 调用以上方法进行下载
        getBlob(url).then(blob => {
          saveAs(blob, filename);
        });
      },
      close(){
        this.visible=false
      },
      submit(){
        console.log(this.dataForm)
        this.$refs['form'].validate((valid)=>{
          if (valid){
            this.fullscreenLoading=true
            this.loading=true
            this.$http({
              url:this.$http.adornUrl('/v1/worker/resume/in/export'),
              method:'POST',
              data:this.$http.adornData({'list':this.dataList})
            }).then(({data})=>{
              this.fullscreenLoading=false
              this.$message({
                message: data.msg,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.loading=false
                  this.visible=false
                  this.$emit('refreshDataList')
                }
              })
            }).catch(()=>{
              this.loading=false
              this.fullscreenLoading=false
            })
          }
        })
      }
    }
  }
</script>
